package cn.dengta.webapp.trade.service;

import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.Resource;

import cn.dengta.common.model.Status;
import cn.dengta.context.model.RedisKey;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.trade.dao.UserWhiteAccountDao;
import cn.dengta.webapp.user.entity.UserWhiteAccount;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.codeplayer.util.StringUtil;
import me.codeplayer.util.X;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static cn.dengta.webapp.base.entity.BizEntity.STATUS;
import static cn.dengta.webapp.user.entity.UserWhiteAccount.TYPE;
import static cn.dengta.webapp.user.entity.UserWhiteAccount.USER_ID;

/**
 * IP登录账号白名单：在白名单内的账号允许通过【任意IP】进行登录
 *
 * @author wxm
 * @since 2022/7/6 12:12
 */
@Service
@Slf4j
public class UserWhiteAccountService extends BaseServiceImpl<UserWhiteAccount, UserWhiteAccountDao, Long> {

	@Resource
	StringRedisTemplate stringRedisTemplate;

	public boolean isEnabled() {
		return StringUtil.notEmpty(stringRedisTemplate.opsForValue().get(RedisKey.IP_WHITE_ACCOUNTS_TOGGLE));
	}

	public boolean allowSkipIpLimit(@Nullable Long userId) {
		if (userId == null || !isEnabled()) {
			return false;
		}
		Boolean contains = stringRedisTemplate.opsForSet().isMember(RedisKey.IP_WHITE_ACCOUNTS, userId.toString());
		return contains != null && contains;
	}

	public boolean exist(Integer type, Long userId) {
		QueryWrapper<UserWhiteAccount> wrapper = new QueryWrapper<UserWhiteAccount>()
				.in(X.isValid(userId), USER_ID, userId)
				.eq(type != null, TYPE, type)
				.ge(STATUS, Status.YES.value);
		return baseDao.exists(wrapper);
	}

	public List<UserWhiteAccount> getListByType(Integer type) {
		QueryWrapper<UserWhiteAccount> wrapper = new QueryWrapper<UserWhiteAccount>()
				.eq(type != null, TYPE, type)
				.ge(STATUS, Status.YES.value);
		return baseDao.selectList(wrapper);
	}

	/**
	 * 获取在线线下女主播
	 */
	public List<UserWhiteAccount> selectOffLineAnchor() {
		return baseDao.selectOffLineAnchor();
	}

	public void insertLimitLog(Long id, Long userId, String remark) {
		baseDao.insertLimitLog(id, userId, remark);
	}

}
